/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package risksim;

import java.util.Arrays;
import java.util.Random;

/**
 *
 * @author victor
 */
public class BaseSim {
    private static Random random = new Random();

    /**
     * Simulates a single round.
     * The dice arrays must be sorted accending; (eg. Arrays.sort()).
     * @param totals An array of the total number of attacks
     * and defenders. This array is modified. The values in
     * this array after this  method runs reflects the results
     * of the 'combat' given the arrays of dice values. The
     * attacker's total comes first in the array.
     * @param atks The dice values for the attackers, must be sorted
     * @param defs The dice values for the defenders, must be sorted
     */
    public static void optimizedSingle(int[] totals, int[] atks, int[] defs) {
        int as = atks.length, ds = defs.length;
        int pairs = Math.min(as, ds);

        for (int i = 0; i < pairs; i++) {
            if (atks[as-1-i] > defs[ds-1-i])
                totals[1]--;
            else
                totals[0]--;
        }
        return;
    }

    /**
     * Simulates a single round. Dice do not need to be given
     * in sorted order.
     * @param totals An array of the total number of attacks
     * and defenders. This array is modified. The values in
     * this array after this  method runs reflects the results
     * of the 'combat' given the arrays of dice values. The
     * attacker's total comes first in the array.
     * @param atks The dice values for the attackers
     * @param defs The dice values for the defenders
     */
    public static void runSingleRound(int[] totals, int[] atks, int[] defs) {
        Arrays.sort(atks);
        Arrays.sort(defs);
        optimizedSingle(totals, atks, defs);
    }

    /**
     * Fills the array with random dice values.
     * @param dice The array to fill.
     */
    public static void randfill(int[] dice) {
        for (int i = 0; i < dice.length; i++) {
            dice[i] = random.nextInt(6) + 1;
        }
    }

    public static void runRawSim(int[] totals) {
        int[] atks = {0, 0, 0};
        int[] defs = {0, 0};
        while (totals[0] > 0 && totals[1] > 0) {
            if (totals[0] < atks.length)
                atks = new int[totals[0]];
            if (totals[1] < defs.length)
                defs = new int[totals[1]];
            randfill(atks);
            randfill(defs);
            runSingleRound(totals, atks, defs);
        }
        return;
    }
}
